<template>
  <div class="release_to">
    <van-overlay :show="showPage" type="primary"/>
    <titleVue @close="close" :title="title_text"></titleVue>
    <div class="policy">
      <!--        表单内容-->
      <div class="content">
        <van-form @submit="onSubmit" validate-first>
          <!--   作品名称-->
          <div class="box">
            <div class="title">
              <span>* </span><b>作品名称</b>
            </div>
            <van-field
                class="input description"
                v-model="nameVal"
                maxlength="100"
                rows="1"
                autosize
                type="textarea"
                style="max-height: 5rem; overflow: auto;"
                show-word-limit
                placeholder="请输入作品名称"

                :rules="[{ required: true, message: '请输入作品名称' }]"
            />
          </div>
          <!--   作品类型-->
          <div class="box">
            <div class="title">
              <span>* </span><b>作品类型</b>
            </div>
            <div class="picker">
              <div style="display: flex;justify-content: left">
                <van-field class="input"
                           readonly
                           clickable
                           name="picker"
                           v-model="p_type_val"
                           placeholder="请选择作品类型"
                           @click="show_p_type_(true)"
                           :rules="[{ required: true, message: '请选择作品类型' }]"
                />
                <!--   图标-->
                <van-icon name="play"
                          color="#f79100"
                          size="1.2rem"
                          class="icon"
                          style="transform: rotate(90deg);margin-left: -2.6rem"
                />
              </div>
              <van-popup v-model:show="show_p_type" position="bottom" get-container="body">
                <van-picker
                    title="选择作品类型"
                    show-toolbar
                    :columns="p_type_columns"
                    @confirm="on_p_type"
                    @cancel="onCancel(0, true)"
                />
              </van-popup>
            </div>
          </div>

          <!--    所在区域-->
          <div class="box">
            <div class="title">
              <span>* </span><b>所在区域</b>
            </div>
            <div class="picker">

              <div style="display: flex;justify-content: left">
                <!--                                <van-field class="input"
                                                           readonly
                                                           clickable
                                                           name="picker"
                                                           :value="area_val"
                                                           placeholder="请输入您所在的区域"
                                                           @click="show_area = true"
                                                           :rules="[{ required: true, message: '请输入您所在的区域' }]"
                                                />-->

                <van-field
                    class="input"
                    v-model="result"
                    readonly
                    name="area"
                    placeholder="点击选择省市区"
                    @click="showArea = true"
                    :rules="[{ required: true, message: '点击选择省市区' }]"
                />
                <van-popup v-model:show="showArea" position="bottom">
                  <van-area
                      :area-list="areaList"
                      @confirm="onConfirm"
                      @cancel="showArea = false"
                  />
                </van-popup>
                <!--   图标-->
                <van-icon name="play"
                          color="#f79100"
                          size="1.2rem"
                          class="icon"
                          style="transform: rotate(90deg);margin-left: -2.6rem"
                />
              </div>
              <van-popup v-model="show_area" position="bottom" get-container="body">
                <van-picker
                    title="选择您所在的区域"
                    show-toolbar
                    :columns="area_columns"
                    @confirm="on_area"
                    @cancel="onCancel(2, true)"
                />
              </van-popup>

            </div>
          </div>

          <!--   详细地址-->
          <div class="box">
            <div class="title">
              <span>* </span><b>详细地址</b>
            </div>
            <van-field
                class="input description"
                v-model="address"
                rows="1"
                autosize
                type="textarea"
                style="max-height: 5rem; overflow: auto;"
                placeholder="请输入详细地址"
                :rules="[{ required: true, message: '请输入详细地址' }]"
            />
          </div>

          <!--   作品介绍-->
          <div class="box">
            <div class="title">
              <span>* </span><b>作品介绍</b>
            </div>
            <div class="picker description">
              <van-field
                  class="input"
                  v-model="p_description"
                  rows="4"
                  autosize
                  type="textarea"
                  style="max-height: 10rem; overflow: auto;"
                  placeholder="请详细介绍您的作品，以展示对作品的理解"
                  :rules="[{ required: true, message: '请详细介绍您的作品，以展示对作品的理解' }]"
              />
            </div>
          </div>

          <!--   作品照片-->
          <div class="box">
            <div class="title">
              <span>* </span><b style="margin: -0.1rem 0 0.2rem 0">作品照片</b>
            </div>
            <div class="picker">
              <van-field name="uploader" style="padding: 0">
                <template #input>
                  <van-uploader
                      v-if="is_update"
                      :max-count="10"
                      preview-size="3.5rem"
                      v-model="uploader"
                      :multiple="true"
                      accept="image/*"
                      :rules="[{ required: true, message: '请至少上传一张照片' }]"
                      @oversize="onOversize"
                      :max-size="15 * 1024 * 1024"
                      multiple/>
                  <van-uploader
                      v-else
                      accept="image/*"
                      :max-count="10"
                      :multiple="true"
                      preview-size="3.5rem"
                      v-model="uploader"
                      @oversize="onOversize"
                      :max-size="15 * 1024 * 1024"
                      :rules="[{ required: true, message: '请至少上传一张照片' }]"
                  />
                </template>
              </van-field>
            </div>
          </div>

          <!--    底部提交按钮-->
          <div class="submit">
            <div class="left">
              <van-checkbox
                  v-model="is_check"
                  shape="square">
              </van-checkbox>
              <span>勾选表示您已认真阅读并同意遵守<a href="javascript:void(0)" @click="read_policy">《隐私政策及免费声明》</a></span>
            </div>
            <div class="right">
              <button v-if="is_update" native-type="submit">修改提交</button>
              <button v-else native-type="submit">提交</button>
            </div>
          </div>
        </van-form>
      </div>
    </div>
  </div>
</template>

<script>
import titleVue from "../../title.vue";
import Util from "../../../../utils/util";
import {ref} from 'vue';
import { areaList } from '@vant/area-data';
import {Dialog, Toast} from 'vant'
export default {

  name: 'ReleaseTo',
  components: {
    titleVue
  },
  inject: ['$baseUrl','$apiUrl', '$headImgUrl'],
  mounted() {
      var id = Util.getUrlByHref('id');
    if (id > 0) {
      this.proId = id
      this.is_update = true
      this.title_text = '修改'
      this.echoData()
      this.show_p_type_(false)
    }
    this.initData()
  },
  setup() {
    const result = ref('');
    const showArea = ref(false);
    const onConfirm = (areaValues) => {
      showArea.value = false;
      result.value = areaValues
          .filter((item) => !!item)
          .map((item) => item.name)
          .join('/');
    };
    return {
      result,
      areaList,
      showArea,
      onConfirm,
    };
  },
  data() {
    return {
      createTime: '', // 创建时间
      title_text: '新建发布',
      nameVal: '',        //作品名称 临时值
      p_type_val: '',     //作品类型 临时值
      jy_type_val: '',    // 交易类型 临时值
      area_val: '',        // 所在区域 临时值
      p_type_columns: [], //作品类型 数组
      p_type_columns_: [], //作品类型 临时数组
      jy_type_columns: [], // 交易类型 数组
      area_columns: [],   // 所在区域 数组
      show_p_type: false, //作品类型 选择器
      show_jy_type: false, // 交易类型 选择器
      show_area: false,     // 所在区域 选择器
      p_description: '',  //作品介绍
      remark: '', //作品交换意向
      uploader: [],       //作品照片
      phone_type: '',     // 联系方式
      product_price: '', //作品价格
      sell_price: '', // 出售价格
      is_check: false, // 是否勾选隐私政策
      showPage: false, // 是否显示遮罩层
      selectedPType: [], // 保存选择的数据
      activeIndexList: [],
      result2: [],
      shouquanShow: false,//授权页面是否显示
      is_update: false, // 是否为修改操作
      proId: -1, // 商品id
      produc_imgs: [], // 商品图片key
      delete_imgs: [], // 删除的图片key
      no_delete_imgs: [], // 不需要删除的图片key
      imgFile: [], // 新上传的图片
      address: '',  // 详细地址
    }
  },

  methods: {
    // 初始化数据
    async initData() {
      console.log('发送请求')
      let url = this.$apiUrl + '/product/getProInfo'
      const {data: res} = await this.$http.get(url)
      if (res.code === 200) {
        console.log('响应结果~~~~~', res)
        let arr = res.data;
        for (let i = 0; i < arr.length; i++) {
          let p_type = {
            index: i,
            p_value: arr[i].p_value,
            p_number: arr[i].p_number
          }
          this.p_type_columns.push(arr[i].p_value)
        }
      }
    },
    // 回显数据
    async echoData() {
      console.log('发送请求')

      let userId = localStorage.getItem('user_id');
      let phone = localStorage.getItem('phone');
      let url = this.$apiUrl + '/product/echoProductInfoById'
        const {data: res} = await this.$http.post(url,{
            proId: this.proId,
            userId: userId,
            phone: phone
        })

      console.log('响应结果~~~~~', res)
      if (res.code === 200) {
        this.nameVal = res.data.name; // 名称
        let pTypeArr = res.data.production_type.replace(/\s+/g, '').split(",").map(item => item.trim());
        this.activeIndexList = pTypeArr; //作品类型
        this.p_type_columns_ = pTypeArr;
        this.p_type_val = pTypeArr.toString();

        this.area_val = res.data.area; // 地区
        this.result = this.area_val;
        this.address = res.data.address; // 详细地址

        this.phone_type = res.data.phone; // 联系方式
        this.createTime = res.data.createTime; // 发布时间

        this.p_description = res.data.description.replace(/\\n/g, "\n"); //作品介绍
        let imgs = res.data.imgs.split(",").map(item => item.trim());
        //作品照片
        for (let i = 0; i < imgs.length; i++) {
          let url = this.$headImgUrl + imgs[i];
          var imgObj = {index: i, url: url, isImage: true}
          this.uploader.push(imgObj);
          this.produc_imgs.push(imgs[i])
        }
      }
    },
    // 选择中 点击取消按钮
    onCancel(num, flag) {
      if (num === 0) {
        flag ? this.p_type_val = '' : true
        this.show_p_type = false
      } else if (num === 1) {
        flag ? this.jy_type_val = '' : true
        this.show_jy_type = false
      } else if (num === 2) {
        flag ? this.area_val = '' : true
        this.show_area = false
      }
    },
    // 选择作品类型 点击确认按钮
    on_p_type(value) {
      this.p_type_val = value
      this.onCancel(0, false)
    },
    // 选择交易类型 点击确认按钮
    on_jy_type(value) {
      this.jy_type_val = value
      this.onCancel(1, false)
      if (this.jy_type_val === '交换' || this.jy_type_val === '赠送') {
        this.sell_price = 0;
      } else {
        this.sell_price = '';
      }
    },
    // 选择所在区域 点击确认按钮
    on_area(value) {
      this.area_val = value.replace(/\s+/g, '')
      this.onCancel(2, false)
    },
    //作品价格 失去焦点
    onrequired(num) {
      if (num === 1) {
        if (this.product_price != '0') {
          // 去除价格前的0
          this.product_price = this.product_price.replace(/^0+/, '');
        }
        let match = this.product_price.match(/\.(\d+)/);
        // 如果存在小数点，则只保留两位小数
        if (match !== null) {
          this.product_price = this.product_price.slice(0, match.index + 3);
        }
      } else {
        if (this.sell_price != '0') {
          // 去除价格前的0
          this.sell_price = this.sell_price.replace(/^0+/, '');
        }
        // 获取小数点后的数子
        let match = this.sell_price.match(/\.(\d+)/);
        // 如果存在小数点，则只保留两位小数
        if (match !== null) {
          this.sell_price = this.sell_price.slice(0, match.index + 3);
        }
      }
    },
    // 校验函数返回 true 表示校验通过，false 表示不通过
    required(val) {
      if (!val || val.trim() === '') {
        // 输入框为空的情况
        return false
      }
      return true;
    },
    // 校验手机号
    validatePhone(val) {
      // 手机号正则表达式
      const reg = /^[1][3-9][0-9]{9}$/; // 手机号正则表达式
      if (!reg.test(val)) {
        return false
      } else {
        return true
      }
    },
    // 点击提交按钮
    onSubmit() {
      // 判断是否上传了照片
      if (this.uploader.length === 0) {
        console.log('判断是否上传了照片')
        Toast('请至少上传一张照片');
        return
      }
      // 是否勾选了隐私政策
      if (this.is_check) {
        Dialog.confirm({
          title: '是否提交',
          message: `<span>是否将<span style="color: #f79305">${this.nameVal}信息发布到信息广场？</span></span>`,
          cancelButtonText: '继续编辑',
          allowHtml:true,
          confirmButtonText: '是，提交',
          confirmButtonColor: '#f79305'
        })
            .then(() => {
              // on confirm
              console.log('提交')
              // 修改
              if (this.is_update) {
                // 新增
                this.update();
              } else {
                this.save();
              }
            })
            .catch(() => {
              // on cancel
              console.log('继续编辑')
            });
      } else {
        console.log('同意隐私政策后才能 提交')
        Toast('请认真阅读用户协议及隐私政策');
      }
    },
    // 关闭当前窗口
    close() {
      this.va.close()
    },
    // 点击阅读政策
    read_policy() {
      this.shouquanShow = true;
      //console.log("阅读政策")
    },
    // 用户是否同意协议
    userApprove(approve) {
      if (approve) {
        this.is_check = true;
      }
      this.shouquanShow = false;

    },
    save() {
      this.showPage = true;
      let phone = localStorage.getItem('phone');
      let userId = localStorage.getItem('user_id');
      let userName = localStorage.getItem('user_name');
      console.log('保存数据')
      const formData = new FormData()
      formData.append('name', this.nameVal)
      formData.append('productionType', this.p_type_val)
      formData.append('result', this.result)
      formData.append('address', this.address)
      formData.append('description', this.p_description)
      formData.append('phone', phone)
      formData.append('userId', userId)
      formData.append('createName', userName)
      this.uploader.forEach(img => {
        formData.append('imgs', img.file)
      })
      Toast.loading({
        duration: 0, // 持续展示 toast
        message: '发布中...',
        forbidClick: true,
      });
      // 定义标志变量
      var flag = false;
      const url = this.$apiUrl + '/product/saveProduct';
      this.$http.post(url, formData, {
        headers: {
          'Content-type': 'multipart/form-data'
        }
      })
          .then((result2) => {
            flag = true; // 请求完成
            if (result2.status == 200 && result2.data.code === 200) {
              console.log(result2)
              this.showPage = false;
              Toast.success('发布文案');
              this.$router.push('/AppHome/Home')
            } else {
              console.log(result2)
              this.showPage = false;
              Toast.fail('发布失败，请重新发布');
            }
          })
          .catch((error) => {
            flag = true; // 请求完成
            console.log(error);
            this.showPage = false;
            Toast.fail('作品发布失败!!!');
          })
          .finally(() => {
            if (flag) {
              Toast.clear(); // 关闭 loading
            }
          });
    },
    update() {
        console.log('修改提交~~~')
      this.showPage = true;
      // 过滤出不需要删除的图片
      this.no_delete_img = this.uploader.filter(item => item.index != undefined)
      // 过滤出新上传的图片
      this.imgFile = this.uploader.filter(item => item.index == undefined)
      console.log(this.imgFile, '新上传的图片')
      // 过滤出已经删除的图片key
      let len = this.produc_imgs.length
      let noLen = this.no_delete_img.length;
      console.log(len)
      // 判断是否存在不需要删除的图片 有则过滤出来
      if (noLen > 0) {
        for (let i = 0, j = 0; i < len; i++) {
          if (this.no_delete_img[j].index !== i) {
            this.delete_imgs.push(this.produc_imgs[i])
          } else {
            if (j < noLen - 1) {
              j++;
            }
          }
        }
        // 截取出不需要删除的图片key
        for (let i = 0; i < noLen; i++) {
          this.no_delete_img[i] = this.no_delete_img[i].url.replace(this.$headImgUrl, '')
        }
      } else if (this.imgFile.length > 0 && noLen === 0) {
        for (let i = 0; i < len; i++) {
          this.delete_imgs.push(this.produc_imgs[i])
        }
      }
      console.log('保存修改后的数据')
      const formData = new FormData()
      formData.append('proId', this.proId)
      formData.append('name', this.nameVal)
      formData.append('productionType', this.p_type_val)
      formData.append('result', this.result)
      formData.append('address', this.address)
      formData.append('description', this.p_description)
      formData.append('deleteImgs', this.delete_imgs)
      formData.append('noDeleteImg', this.no_delete_img)
      this.imgFile.forEach(img => {
        formData.append('imgs', img.file)
      })
        console.log(formData, 'formData')
      Toast.loading({
        duration: 0, // 持续展示 toast
        message: '发布中...',
        forbidClick: true
      });

      // 定义标志变量
      var flag = false;
      const url = this.$apiUrl + '/product/updateProduct';
      this.$http.post(url, formData, {
        headers: {
          'Content-type': 'multipart/form-data'
        }
      })
       .then((result2) => {
           console.log(result2)
            flag = true; // 请求完成
            if (result2.code == 200) {
              this.showPage = false;
              this.$message.success("发布成功");
              // this.$router.push('/AppHome/ReleaseSuccess')
            } else {
              console.log(result2)
              this.showPage = false;
              this.$message.error("发布失败，请重新发布");
            }
          })
       .catch((error) => {
            console.log(error);
            flag = true; // 请求完成
            this.showPage = false;
            this.$message.error("商品发布失败!!!");
          })
       .finally(() => {
            if (flag) {
              Toast.clear(); // 关闭 loading
            }
          });
    },
    // Toast.clear(); // 关闭 loading
    // 回显作品类型按钮选中状态
    show_p_type_(flag) {
      console.log(this.$refs)
      if (flag) {
        this.show_p_type = true
      }
      var length = this.activeIndexList.length
      this.$nextTick(() => {
        if (length > 0) {
          var len = this.p_type_columns.length
          for (let i = 0; i < len; i++) {
            var item = this.p_type_columns[i]
            const indexOf = this.activeIndexList.indexOf(item)
            if (indexOf !== -1) {
              if (flag) {
                // 数组里面有相同的数据，切换选中状态
                this.$refs.checkboxes[i].toggle(true)
              } else {
                // 数组里面有相同的数据，切换选中状态
                this.$refs.checkboxes[i].toggle()
              }

            }
          }
        }
      })
    },
    // 弹窗确定按钮
    confirm() {
      this.result2 = []
      this.show_p_type = false
      this.activeIndexList = []
      for (let i = 0; i < this.p_type_columns_.length; i++) {
        var item = this.p_type_columns_[i]
        this.activeIndexList.push(item)
      }
      this.p_type_val = this.activeIndexList.toString()
    },
    // 弹窗取消按钮
    cancel() {
      this.result2 = []
      this.p_type_columns_ = []
      this.show_p_type = false
    },
    // 弹窗多选
    toggle(item, index) {
      this.$refs.checkboxes[index].toggle()
      const indexOf = this.p_type_columns_.indexOf(item)
      if (indexOf !== -1) {
        // 数组里面有相同的数据，去掉选中的值,代表点击的行已被点击过，这次点击则删除选中数组里面的值
        this.p_type_columns_.splice(indexOf, 1)
      } else {
        // 数组里面没有相同的数据
        this.p_type_columns_.push(item)
      }
    },
  onOversize() {
      this.$message.warning("图片大小不能超过 10MB");
  },
  }
}
</script>

<style scoped lang="less">
.release_to {
  overflow: hidden;

  .policy {
    overflow: auto;
    height: calc(100vh - 2.75rem);
    // 表单内容
    .content {
      padding: 1rem;

      .box {
        font-size: 14px;
        margin-bottom: 0.7rem;

        .title {
          display: flex;
          left: 0;

          span {
            color: red;
            margin-right: 0.4rem;
          }

          b {
            margin-bottom: 0.5rem;
          }
        }

        .input {
          border: 1.5px solid #e9eaeb;
          padding: 0.3rem 1rem;
        }

        .description {
          font-size: 12px;
        }

        //.popup-bg {
        //    background: rgba(0, 0, 0, 0.5);
        //    width: 100%;
        //    height: 100%;
        //    position: fixed;
        //    top: 0;
        //    left: 0;
        //    z-index: 6;
        //}

        //.btn {
        //    display: flex;
        //    justify-content: space-between;
        //}

        //.popup {
        //    position: absolute;
        //    bottom: 0;
        //    left: 0;
        //    z-index: 100;
        //    width: 100%;
        //    height: 400px;
        //    overflow: auto;
        //    border-top-left-radius: 8px;
        //    border-top-right-radius: 8px;
        //    background: #fff;
        //    text-align: left;
        //}

        //.cancle {
        //    color: #969799;
        //    padding: 15px 0 15px 18px;
        //    font-size: 14px;
        //}
        //
        //.confirm {
        //    padding: 15px 18px 15px 0;
        //    font-size: 14px;
        //}
      }

      .price {
        display: flex;

        .box {
          flex: 1;
        }

        .box:nth-child(1) {
          margin-right: 0.6rem;
        }

        .box:nth-child(2) {
          margin-left: 0.6rem;
        }
      }
    }

    // 底部提交按钮
    .submit {
        display: flex;
        justify-content: space-between;
        margin-top: 7.5rem;
      .left {
        display: flex;
        justify-items: center;

        span {
          color: #a2a3a4;
          font-size: 15px;
          width: 12rem;
          margin-left: 1rem;

          a {
            color: #f79100;
          }
        }
      }

      .right {
        button {
          background-color: #f79100;
          color: #ffffff;
          width: 4.6rem;
          height: 2.53rem;
          line-height: 2.53rem;
          font-weight: 600;
          text-align: center;
          border-radius: 8px;
          border: none;
        }
      }
    }
  }
}

.policy::-webkit-scrollbar {
  /* 隐藏滚动条 */
  display: none;
}

.input::-webkit-scrollbar {
  /* 隐藏滚动条 */
  display: none;
}
</style>
